﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Tasks;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Phone.Net.NetworkInformation;
using System.Diagnostics;
//using FileStoreService;
using System.ServiceModel;
using System.Globalization;
using CommonControls.AboutApps;
using HomeBuyerTools.FileStoreService;


namespace CommonControls.ClassFiles
{
    public class Exceptions
    {
        private static bool isSendErrors;
        public static bool IsSendErrors
        {
            get
            {
                var settings = IsolatedStorageSettings.ApplicationSettings;
                if (settings.Contains("SendErrors"))
                {
                    if (bool.Parse(settings["SendErrors"].ToString()))
                        isSendErrors = true;
                    else
                        isSendErrors = false;
                }
                return isSendErrors;
            }
        }

        private static bool isNetworkAvailable;
        public static bool IsNetworkAvailable
        {
            get
            {
                var settings = IsolatedStorageSettings.ApplicationSettings;
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    if (NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None)
                        isNetworkAvailable = true;
                    else
                        isSendErrors = false;
                }
                return isNetworkAvailable;
            }
        }

        //Saving Detailed Exceptions
        public static void SaveOrSendExceptions(string message, IDictionary data)
        {
            message = message + "\n Extra Data \n";
            foreach (DictionaryEntry d in data)
                message = message + d.Key + " -> " + d.Value + "\n";
            message = message + BuildMailMessage();
            SaveData(message);
        }

        public static void SaveData(string message)
        {
            try
            {
                SaveExceptionInLocalStorage(message);
                if (Exceptions.IsSendErrors && Exceptions.IsNetworkAvailable)
                {
                    string Subject = "Errors";
                    Service1Client service = new Service1Client();
                    service.SendMailAsync("userexception@hotmail.com", "wp7errors@lartsoft.com", Subject, message);
                    service.SendMailCompleted += new EventHandler<SendMailCompletedEventArgs>(service_SendMailCompleted);
                }
            }
            catch (Exception e)
            {
                string excepmess = "Exception in SaveData Method In Exceptions file.\n\n" + e.Message + "\n\n StackTrace :- \n" + e.StackTrace;
                SaveExceptionInLocalStorage(excepmess);
            }
        }

        static void service_SendMailCompleted(object sender, SendMailCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                FaultException fault = e.Error as FaultException;
                SaveExceptionInLocalStorage(e.Error.Message);
            }
        }

        public static void SaveExceptionInLocalStorage(string Message)
        {
            try
            {
                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    XDocument doc;
                    IsolatedStorageFileStream isoStream;
                    if (!isoStore.FileExists("/DetailedException.xml"))
                    {
                        isoStream = new IsolatedStorageFileStream("/DetailedException.xml", FileMode.Create, isoStore);
                        doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                                    new XElement("exceptions",
                                            new XElement("exceptionmessage", Message)));
                        doc.Save(isoStream);
                        isoStream.Close();
                    }
                    else
                    {
                        isoStream = new IsolatedStorageFileStream("/DetailedException.xml", FileMode.Open, isoStore);
                        doc = XDocument.Load(isoStream);
                        isoStream.Close();
                        doc.Root.Add(new XElement("exceptionmessage", Message));
                        isoStream = new IsolatedStorageFileStream("/DetailedException.xml", FileMode.Create, isoStore);
                        doc.Save(isoStream);
                        isoStream.Close();
                    }
                }
            }
            catch
            {

            }
        }


        public static string BuildMailMessage()
        {
            string DeviceId = "";
            if (ExtendedPropertyHelper.GetDeviceUniqueID() != null)
            {
                byte[] id = ExtendedPropertyHelper.GetDeviceUniqueID();
                DeviceId = BitConverter.ToString(id);


            }
            string body = "\n\n\nDateTime : " + System.DateTime.Now +
                "\nCulture : " + CultureInfo.CurrentCulture.Name +
                "\nDevice Name : " + ExtendedPropertyHelper.GetDeviceModel() +
                "\nStandard Time : " + TimeZoneInfo.Local.StandardName +
                "\nManufacturer : " + ExtendedPropertyHelper.GetManufacturer() +
                "\nApp Name : " + PhoneHelper.GetAppAttribute("Title") +
                "\n Version:" + PhoneHelper.GetAppAttribute("Version");

            return body;
        }
    }
}
